package cn.jcet.mapreduce.tables;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

/**
 * @author 鲜磊
 * @Date 2020/12/16 10:40
 */
public class TablesMapper extends Mapper<LongWritable,Text,Text,TableBean> {

    private TableBean v = new TableBean();

    private Text k = new Text();

    private String name;
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        
        // 获取切片信息
        FileSplit inputSplit = (FileSplit) context.getInputSplit();
        // 获取切片名称
        name = inputSplit.getPath().getName();
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 转为字符串
        String line = value.toString();
        if (name.startsWith("order")){
//            1001	01	1
            // 切割
            String[] fields  = line.split("\t");
            // 对数据进行封装
            v.setId(fields[0]);
            v.setPid(fields[1]);
            v.setAmount(Integer.parseInt(fields[2]));
            v.setPname("");
            v.setFlag("order");
            // 作为key pid
            k.set(fields [1]);
        }else {
//            01	小米
            String[] fields  = line.split("\t");
            v.setId("");
            v.setPid(fields[0]);
            v.setAmount(0);
            v.setPname(fields[1]);
            v.setFlag("pd");
            // 作为key
            k.set(fields[0]);
        }
        // 写出
        context.write(k,v);
    }
}
